package com.wzdigit.wms.common.utils;

import com.wzdigit.framework.Shift;
import com.wzdigit.wms.common.entity.StatusCode;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class ValidatorUtil {

	private final static Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

	@SuppressWarnings("rawtypes")
	public static <T> void validator(T object) {
		Set violations = VALIDATOR.validate(object);
		// 如果有验证信息，则将第一个取出来包装成异常返回
		if (violations != null && violations.size() > 0) {
			String[] messages = new String[violations.size()];
			Iterator iterator = violations.iterator();
			int i = 0;
			while (iterator.hasNext()) {
				ConstraintViolation violation = (ConstraintViolation) iterator.next();
				messages[i] = violation.getMessage();
				i++;
			}
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS, messages);
		}
	}
	
	@SuppressWarnings("rawtypes")
	public static <T> List<String> validatorMessages(T object) {
		Set violations = VALIDATOR.validate(object);
		// 如果有验证信息，则将第一个取出来包装成异常返回
		if (violations != null && violations.size() > 0) {
			List<String> messages = new ArrayList<String>(violations.size());
			Iterator iterator = violations.iterator();
			while (iterator.hasNext()) {
				ConstraintViolation violation = (ConstraintViolation) iterator.next();
				messages.add(violation.getMessage());
			}
			return messages;
		} else {
			return new ArrayList<String>(0);
		}
	}

	public static void validator(BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			List<ObjectError> errors = bindingResult.getAllErrors();
			String[] messages = new String[errors.size()];
			for (int i = 0; i < errors.size(); i++) {
				messages[i] = errors.get(i).getDefaultMessage();
			}
			Shift.fatal(StatusCode.INVALID_MODEL_FIELDS, messages);
		}
	}
}
